<?php

namespace Front\Controller;

use Core\Config;
use Core\Constant;
use Core\Controller\FrontBaseController;
use Core\Exception\BusinessException;
use Core\Helper\AdminInputHelper;
use Core\Session\FrontSessionHelper;
use Exception;
use Logger;
use Zend\View\Model\JsonModel;


class LoginController extends FrontBaseController {

    public function indexAction() {
        $this->initPageWithLayout();
        return $this->getViewModel();
    }

    public function loginAction()
    {
        try {
            $password = $this->params()->fromPost('password');
            $userName = $this->params()->fromPost('username');
            $userTable = $this->getTableFinder()->getUserTable();
            $userItem = $userTable->getUserByEmail($userName);
            if($userItem){
                $digestService = $this->getDigestService();
                if($userItem->password == $digestService->getUserPassword($userName, $password)){
                    FrontSessionHelper::setUser($userItem);
                    $date = new \DateTime();
                    FrontSessionHelper::setLoginTime($date);
                }
                else{
                    throw new \Core\Exception\BusinessException('Thông tin đăng nhập không hợp lệ');
                }
            }else{
                throw new \Core\Exception\BusinessException('Thông tin đăng nhập không hợp lệ');
            }

            return new JsonModel(array('success'=>true));

        }
        catch (Exception $e) {
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_FRONT_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function logoutAction()
    {
        try {

            FrontSessionHelper::setUser(null);
            return new JsonModel(array('success'=>true));
        }
        catch (Exception $e) {
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_FRONT_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }


    public function registerAction() {
        $this->initPageWithLayout();
        return $this->getViewModel();
    }


///register-user',{email:email,password:password, passwordretype:passwordretype,
//                name:name

     public function registerUserAction()
    {
        try {
            $email = $this->params()->fromPost('email');
            $password = $this->params()->fromPost('password');
            $passwordretype = $this->params()->fromPost('passwordretype');
            $name = $this->params()->fromPost('name');

            //validate
            //check if email exist
            $email = AdminInputHelper::filterStringTrim($email);
            $validatorDto = AdminInputHelper::validateEmail($email);
            if(!$validatorDto->isValid()) throw new BusinessException($validatorDto->getMessageStr());
            $userTable = $this->getTableFinder()->getUserTable();
            $user = $userTable->getUserByEmail($email);
            if($user)
                throw new BusinessException('Đã tồn tại email: '.$email.' trên hệ thống');
            //check if password too short
            $validatorDto = AdminInputHelper::validateStringLength($password, 6);
            if(!$validatorDto->isValid()) throw new BusinessException($validatorDto->getMessageStr());
            //check if password the same
            if($password != $passwordretype)
                throw new BusinessException('Password nhập vào phải trùng nhau');

            $tmpArr = explode('@',$email);
            $userName = $tmpArr[0];
            if($name){
                $name = AdminInputHelper::filterStringTrim($name);
                $validatorDto = AdminInputHelper::validateStringLength($name,6);
                if(!$validatorDto->isValid()) throw new BusinessException($validatorDto->getMessageStr());
               $userName =  $name;
            }

            $userId = $userTable->insert(array('email'=>$email, 'username'=>$userName,
                'name'=>$name, 'password'=>$password, 'active'=>1, 'status'=>Constant::$USER_STATUS_INACTIVATE));
            //create balance
            $userBalanceTable = $this->getTableFinder()->getUserBalanceTable();
            $userBalanceTable->insert(array('user_id'=>$userId,
                'balance'=>Config::getInitialBalance(),
            ));

            //grant member role to user
            $roleTable = $this->getTableFinder()->getRoleTable();
            $role = $roleTable->getRoleByCode(Constant::$SYSTEM_ROLE_CODE_MEMBER);
            $role->attachUser($userId);

            $activeUrl = Config::getSystemConfig()->front->baseUrl.'/activate?userId=';
            $activateKey =  md5($user->email.'_'.$password);
            $activeUrl = $activeUrl.$activateKey;
            //send mail
            $mailInterface = $this->getMailService();
            $mailInterface->systemSendMail($email, 'Kích hoạt tài khoản', 'Having a nice day. Click to activate: '.$activeUrl);

            FrontSessionHelper::setUser($userTable->getUser($userId));
            $date = new \DateTime();
            FrontSessionHelper::setLoginTime($date);

            return new JsonModel(array('success'=>true, 'username'=>$userName, 'balance'=>Config::getInitialBalance()));
        }
        catch (Exception $e) {
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_FRONT_EXCEPTION);
            return $this->genJsonErrorView($e);
        }


    }
}